package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.model.Message;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.adapter.MsgReceiveItemDelagate;
import com.oracle.zebrafreelytraveling.ui.adapter.MsgSendItemDelagate;
import com.oracle.zebrafreelytraveling.ui.service.WebSocketService;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.GsonUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yydcnjjw on 2017/7/24.
 * 聊天界面窗口
 */
public class ChatActivity extends BaseActitvity implements View.OnClickListener, WebSocketService.onMessageListener {

    //Intent 传参
    //聊天类型
    public static final String CHAT_TYPE = "chatType";
    //group或者好友 的id
    public static final String ID = "groupOrUserId";

    private WebSocketService.ChatBinder mChatBinder;
    private ChatServiceConnection mConnection = new ChatServiceConnection();


    private List<Message> messageList = new ArrayList<>();

    private EditText eTinputText;
    private Button btnSend;
    private RecyclerView msgRecycleView;
    private MultiItemTypeAdapter multiItemTypeAdapter;

    //聊天类型
    private String chatType;
    //id
    private int id;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        getIntentData();
        startServiceToWebSocketService();
        initView();
    }

    private void getIntentData(){
        Intent intent = getIntent();
        chatType = intent.getStringExtra(CHAT_TYPE);
        id = intent.getIntExtra(ID, -1);
    }

    private void initView() {
        eTinputText = (EditText) findViewById(R.id.input_text);
        btnSend = (Button) findViewById(R.id.send_msg);
        msgRecycleView = (RecyclerView) findViewById(R.id.chat_msg_recycle_view);
        msgRecycleView.setLayoutManager(new LinearLayoutManager(this));
        multiItemTypeAdapter = new MultiItemTypeAdapter(this, messageList);
        multiItemTypeAdapter.addItemViewDelegate(new MsgSendItemDelagate());
        multiItemTypeAdapter.addItemViewDelegate(new MsgReceiveItemDelagate());
        msgRecycleView.setAdapter(multiItemTypeAdapter);

        btnSend.setOnClickListener(this);
    }

    /**
     * 发送消息
     */
    private void sendMessage() {
        String content = eTinputText.getText().toString();
        Message message = null;
        if (!TextUtils.isEmpty(content)) {
            //判断消息类型发送不同消息
            message = new Message();
            message.setContent(content);
            message.setType(Constant.TYPE_SEND);
            message.setSendType(chatType);
            message.setReceiveId(id);
            message.setSendId(UserUtil.getUserInfoFromSP().getUserId());
            if (chatType.equals(Constant.GROUP_MESSAGE) && id != -1) {
                Log.d("chatType", "GROUP_MESSAGE");
                mChatBinder.sendMessage(GsonUtil.getInstance().toJson(message), Constant.GROUP_MESSAGE, id);
            } else if (chatType.equals(Constant.SINGLE_MESSAGE) && id != -1) {
                Log.d("chatType", "SINGLE_MESSAGE");
                mChatBinder.sendMessage(GsonUtil.getInstance().toJson(message), Constant.SINGLE_MESSAGE, id);
            }
        }
        messageList.add(message);
        multiItemTypeAdapter.notifyDataSetChanged();
        msgRecycleView.scrollToPosition(messageList.size() - 1);//将list定位到最后一行
        eTinputText.setText("");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_msg:
                sendMessage();
                break;
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chat;
    }

    private void startServiceToWebSocketService() {
        Intent intent = new Intent(ChatActivity.this, WebSocketService.class);
        intent.putExtra(CHAT_TYPE, chatType);
        intent.putExtra(ID, id);
        startService(intent);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
    }

    private void stopServiceToWebSocketService() {
        Intent intent = new Intent(ChatActivity.this, WebSocketService.class);
        stopService(intent);
        unbindService(mConnection);
    }

    @Override
    public void getReceiveMessageToActive(Message message) {
        //TODO 对消息进行处理判断是什么类型的消息以及发给谁
        String sendType = message.getSendType();
        if (sendType.equals(Constant.GROUP_MESSAGE) || sendType.equals(Constant.SINGLE_MESSAGE)) {
            messageList.add(message);
        } else if (sendType.equals(Constant.SNED_SUCCESS)){
            int position = getFirstSendStateToFalse();
            if (position == -1){
                return;
            }
            messageList.get(position).setSendState(true);
        } else if (sendType.equals(Constant.SEND_FALSE)) {
//            messageList.add();
            //TODO 获取list位置 显示发送失败
            getFirstSendStateToFalse();
        }
        msgRecycleView.scrollToPosition(messageList.size() - 1);//将list定位到最后一行
        multiItemTypeAdapter.notifyDataSetChanged();

    }

    private int getFirstSendStateToFalse(){
        //发送成功的最后一个信息的位置
        for (int i = 0; i < messageList.size(); i++) {
            if (messageList.get(i).getType() == Constant.TYPE_SEND &&
                    !messageList.get(i).isSendState()){
                return i;
            }
        }
        return -1;
    }

    public class ChatServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mChatBinder = (WebSocketService.ChatBinder) service;
            if (mChatBinder != null) {
                mChatBinder.getBindActivityInfo(ChatActivity.this);
                Log.d("chatBinder", "not null");
            } else {
                Log.d("chatBinder", "null");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public static void startChatActivity(Activity activity, String type, int id) {
        Intent intent = new Intent(activity, ChatActivity.class);
        intent.putExtra(CHAT_TYPE, type);
        intent.putExtra(ID, id);
        activity.startActivity(intent);
    }

}
